<?php
/** 
 * @EventListener(onEvent="XContextStartedEvent|XContextClosedEvent")
 */
class XLog4YaxListener implements XEventListener{
	public function onEvent(XEvent $event){
		if($event instanceof XContextStartedEvent){
			return $this->init();
		}
		if($event instanceof XContextClosedEvent){
			return $this->close();
		}
	}
	
	protected function init(){		
		$appenders = XConfig::singleton()->get("project.log4yax.appender");
		if(!$appenders){
			return false;
		}
		$logger =  new XLog4YaxLogger();
		foreach($appenders as $key => $value){
			if(!isset($value['class'])){
				throw new XLog4YaxException("Log4Yax Configuration Error: No appender class of appender {$key}");
			}
			if(!XClassLoader::loader($value['class'])->implementsInterface('XLog4YaxAppender')){
				throw new XLog4YaxException("Log4Yax Configuration Error: Appender class {$value['class']} of appender {$key} must implements XLog4YaxAppender");
			}
			$appender = new $value['class']($key, $value);
			if(!isset($value['layout'])){
				throw new XLog4YaxException("Log4Yax Configuration Error: No layout configuration of appender {$key}");
			}
			if(!isset($value['layout']['class'])){
				throw new XLog4YaxException("Log4Yax Configuration Error: No layout class of appender {$key}");
			}
			if(!XClassLoader::loader($value['layout']['class'])->implementsInterface('XLog4YaxLayout')){
				throw new XLog4YaxException("Log4Yax Configuration Error: Layout class {$value['class']} of appender {$key} must implements XLog4YaxLayout");
			}
			$layout = new $value['layout']['class']($value['layout']);
			$appender->setLayout($layout);
			$logger->addAppender($key, $appender);
		}
		XLog::singleton()->setLogger($logger);
		$logger->log(new XLoggingEvent($this, INFO, "Log4Yax loaded successfully."));
		return true;
	}
	
	protected function close(){
		$logger = XLog::singleton()->logger();
		if($logger){
			$logger->log(new XLoggingEvent($this, INFO, "Log4Yax Closed."));
		}
		return true;
	}
}
?>